/* Utility for transforming plain text into emojified version */

window.emojify = function(text) {
    return emoticonToEmojify(colonEmojify(text));
};

/* Transform :emoji: to its Unicode equivalent */

const colonEmojify = function(text) {
    return text.replace(/:[^ :]*:/g, (pattern) => {
        const raw = pattern.slice(1, -1).toLowerCase();

        /* Put it into the two normal forms, underscores or hyphen, and try
         * each */

        const underscore = raw.replace(/-/g, '_');

        if (window.EMOJIS[underscore])
            return window.EMOJIS[underscore];

        const hyphen = raw.replace(/_/g, '-');

        if (window.EMOJIS[hyphen])
            return window.EMOJIS[hyphen];

        /* Try it as a country name */

        const spaced = raw.replace(/[-_]/g, ' ');
        const country = window.COUNTRY_NAME_TO_ID[spaced];

        if (country) {
            const flagName = 'flag-' + country;

            if (window.EMOJIS[flagName])
                return window.EMOJIS[flagName];
        }

        /* Otherwise, give up and return as-is */

        return pattern;
    });
};

/* Transform :p to Unicode */
const emoticonToEmojify = function(text) {
    let transformed = text;

    for (const emoticon of Object.keys(window.EMOTICON_TO_UNICODE)) {
        transformed = transformed.split(emoticon).join(window.EMOTICON_TO_UNICODE[emoticon]);
    }

    return transformed;
};
